<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="1800px"
    @close="close"
  >
    <el-row :gutter="40">
      <el-col :span="7">
        <template>
          <el-form ref="form" label-width="120px" :model="form" :rules="rules" :disabled="disabled">
            <el-form-item label="上级SKU">
              <el-tag type="danger" v-if="form.parentSku.id">{{form.parentSku.label}}</el-tag>
              <span v-else>无</span>
            </el-form-item>
            <el-form-item label="批次号">
              <el-input v-model.trim="form.no" readonly placeholder="自动生成"/>
            </el-form-item>
            <el-form-item label="BOM工单编码" prop="code">
              <el-input v-model.trim="form.code" clearable/>
            </el-form-item>
            <el-form-item label="生产日期" prop="production_date">
              <el-date-picker v-model.trim="form.production_date" clearable format="yyyy年MM月dd日"
                              value-format="yyyy-MM-dd"/>
            </el-form-item>
            <el-form-item label="重量(KG)" prop="weight">
              <el-input-number :precision="2" :step="0.1" v-model.trim="form.weight" style="width:50%"/>
            </el-form-item>
            <el-form-item label="SKU" prop="sku_id">
              <el-select v-model.trim="form.sku_id" clearable filterable @change="handleChange" style="width: 100%">
                <el-option v-for="(item,key) in sku_list" :value="item.id" :key="key" :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-for="(row) in form.attribute_name" :label="row.input_type === 5 ? row.name+'(%)' : row.name" :key="row.id+'attribute_name'">
              <el-input v-if="row.input_type === 1" v-model="row.value" placeholder="请输入内容" clearable/>
              <el-select v-else-if="row.input_type === 2" v-model="row.value" clearable>
                <el-option v-for="item in row.object" :key="item.name" :value="item.name"></el-option>
              </el-select>
              <el-date-picker v-else-if="row.input_type === 3" v-model="row.value" placeholder="请输入日期" clearable
                              type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"/>
              <el-input-number v-else-if="row.input_type === 4" v-model="row.value" :step="1"
                               placeholder="请输入"/>
              <el-input-number v-else-if="row.input_type === 5"   v-model="row.value" :precision="2"
                               :step="0.01" :max="100" :min="0"/>
            </el-form-item>
            <el-form-item v-for="(row) in form.attribute_spec" :label="row.input_type === 5 ? row.name+'(%)' : row.name" :key="row.id+'attribute_spec'">
              <el-input v-if="row.input_type === 1" v-model="row.value" placeholder="请输入内容" clearable/>
              <el-select v-else-if="row.input_type === 2" v-model="row.value" clearable filterable>
                <el-option v-for="item in row.object" :key="item.name" :value="item.name"></el-option>
              </el-select>
              <el-date-picker v-else-if="row.input_type === 3" v-model="row.value" placeholder="请输入日期" clearable
                              type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"/>
              <el-input-number v-else-if="row.input_type === 4" v-model="row.value" :step="1"
                               placeholder="请输入"/>
              <el-input-number v-else-if="row.input_type === 5"   v-model="row.value" :precision="2"
                               :step="0.01" :max="100" :min="0"/>
            </el-form-item>

            <el-form-item label="处理地点" prop="customer_id">

              <el-select v-model.trim="form.customer_id" clearable filterable  style="width: 100%">
                <el-option v-for="(item,key) in customer_list" :value="item.id" :key="key"
                           :label="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传附件">
              <template v-if="form.file_path">
                <el-link :href="fileRootPath+form.file_path" :underline="false"
                         :download="form.file_path">
                  <el-button icon="el-icon-download" size="small" type="success" plain>下载</el-button>
                </el-link>
                <el-link :underline="false">
                  <el-button @click="delete_file" icon="el-icon-delete" type="danger" plain>删除</el-button>
                </el-link>
              </template>
              <template v-else>
                <attachment-upload typ="bom" @input="changeUrlFile" ref="uploadFile"/>
              </template>
            </el-form-item>
            <el-form-item label="实拍图片" style="height:180px;margin-bottom: 30px">
              <template v-if="form.pic">
                <el-col>
                  <el-image :src="fileRootPath+form.pic" style="width:auto;height:180px"/>
                </el-col>
                <el-col>
                  <el-button @click="delete_img" icon="el-icon-delete">删除图片</el-button>
                </el-col>
              </template>
              <template v-else>
                <Upload ref="uploadPic" typ="sku" @input="changeUrl"/>
              </template>
            </el-form-item>
          </el-form>
        </template>
      </el-col>
      <el-col :span="17">
        <template>
          <el-form ref="formChildren" label-width="120px" :model="form" :rules="rules" :disabled="disabled">
            <div>
              <b>生产拆解子工单</b>
              <el-card class="box-card" style="margin-top: 20px">
                <div slot="header" class="clearfix">
                  <span>名称</span>
                  <el-button style="float: right; padding: 3px 0" icon="el-icon-plus" type="text" v-if="form.is_link"
                             @click="handleAddRow(1)">添加
                  </el-button>
                </div>
                <el-table :data="form.children" style="width: 100%">
                  <el-table-column align="center" type="index" label="序号"></el-table-column>
                  <el-table-column align="center" prop="name" label="sku" width="220" show-overflow-tooltip>
                    <template #default="scope">
                      <el-tooltip :content="getSelectedLabel(scope.row.sku_id)" placement="top" effect="dark">
                      <el-select v-model="scope.row.sku_id" placeholder="请选择"
                                 @change="handleChangeChildren(scope.$index)" clearable filterable>
                        <el-option v-for="(item,key) in sku_list" :value="item.id" :key="key"
                                   :label="item.label" :title="item.label"></el-option>
                      </el-select>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="180" label="重量(KG)">
                    <template #default="scope">
                      <el-tooltip :content="scope.row.weight.toString()" placement="top" effect="dark">
                      <el-input-number v-model.trim="scope.row.weight" :precision="2" :step="0.1" style="width: 100%"/>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="300" label="生产属性">
                    <template #default="scope">
                      <div v-for="(item) in scope.row.attribute_name" :key="item.id + '_table_name'">
                        <el-row :gutter="10">
                          <el-col :span="8">{{ item.name }}<span v-if="item.input_type === 5">(%)</span>:</el-col>
                          <el-col :span="16">
                            <el-input v-if="item.input_type === 1" v-model="item.value" placeholder="请输入内容"
                                      clearable/>
                            <el-select v-else-if="item.input_type === 2" v-model="item.value" clearable>
                              <el-option v-for="(option, key) in item.object" :key="key" :value="option.name"
                                         :label="option.name"></el-option>
                            </el-select>
                            <el-date-picker v-else-if="item.input_type === 3" v-model="item.value"
                                            placeholder="请输入日期" clearable type="date" format="yyyy-MM-dd"
                                            value-format="yyyy-MM-dd"/>
                            <el-input-number v-else-if="item.input_type === 4" v-model="item.value" :step="1"
                                             placeholder="请输入"/>
                            <el-input-number v-else-if="item.input_type === 5"  v-model="item.value" :precision="2"
                                             :step="0.01" :max="100" :min="0"/>
                          </el-col>
                        </el-row>
                      </div>
                      <div v-for="(item) in scope.row.attribute_spec" :key="item.id + '_table_spec'">
                        <el-row :gutter="10">
                          <el-col :span="8">{{ item.name }}<span v-if="item.input_type === 5">(%)</span>:</el-col>
                          <el-col :span="16">
                            <el-input v-if="item.input_type === 1" v-model="item.value" placeholder="请输入内容"
                                      clearable/>
                            <el-select v-else-if="item.input_type === 2" v-model="item.value" clearable>
                              <el-option v-for="(option, key) in item.object" :key="key" :value="option.name"
                                         :label="option.name"></el-option>
                            </el-select>
                            <el-date-picker v-else-if="item.input_type === 3" v-model="item.value"
                                            placeholder="请输入日期" clearable type="date" format="yyyy-MM-dd"
                                            value-format="yyyy-MM-dd"/>
                            <el-input-number v-else-if="item.input_type === 4" v-model="item.value" :step="1"
                                             placeholder="请输入"/>
                            <el-input-number v-else-if="item.input_type === 5"  v-model="item.value" :precision="2"
                                             :step="0.01" :max="100" :min="0"/>
                          </el-col>
                        </el-row>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="percent" label="物料占比" >
                    <template #default="scope">
                      {{ parseFloat(scope.row.weight / form.weight * 100).toFixed(2) }}%
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="200" label="附件">
                    <template #default="scope">
                      <template v-if="scope.row.file_path">
                        <el-link :href="fileRootPath+scope.row.file_path" :underline="false"
                                 :download="scope.row.file_path">
                          <el-button icon="el-icon-download" size="small" type="success" plain>下载</el-button>
                        </el-link>
                        <el-link :underline="false">
                          <el-button @click="delete_file_children(scope.$index)" icon="el-icon-delete" type="danger" plain>删除</el-button>
                        </el-link>
                      </template>
                      <template v-else>
                        <attachment-upload typ="bom" @input="changeUrlFileChildren" ref="uploadFile" :index="scope.$index"/>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" width="150" label="操作">
                    <template #default="scope">
                      <el-button type="primary" icon="el-icon-arrow-up" circle plain
                                 @click.stop="handleUp(scope.$index)"/>
                      <el-button type="warning" icon="el-icon-arrow-down" circle plain
                                 @click.stop="handleDown(scope.$index)"/>
                      <el-button type="danger" icon="el-icon-delete" circle plain
                                 @click.stop="handleDel(scope.$index)"/>
                    </template>
                  </el-table-column>
                  <template #empty>
                    <el-image
                      class="vab-data-empty"
                      :src="require('@/assets/empty_images/data_empty.png')"
                    />
                  </template>
                </el-table>
                <hr/>
                <el-row :gutter="20" class="text-left">
                  <el-col :span="12">
                    <el-form-item label="合计重量(KG):">
                      {{ new Intl.NumberFormat('en-US', {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2
                    }).format(parseFloat(form.children.reduce((sum, item) => sum + item.weight, 0).toFixed(2)))}}
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="合计占比:">
                      {{
                        parseFloat(form.children.reduce((sum, item) => sum + item.weight, 0) / form.weight * 100).toFixed(2)
                      }}%
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20" class="text-left">
                  <el-col :span="12">
                    <el-form-item label="损耗重量(KG):">
                      {{ new Intl.NumberFormat('en-US', {
                      minimumFractionDigits: 2,
                      maximumFractionDigits: 2
                    }).format((form.weight - (form.children.reduce((sum, item) => sum + item.weight, 0))).toFixed(2))}}
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="损耗占比:">
                      {{
                        parseFloat(100 - form.children.reduce((sum, item) => sum + item.weight, 0) / form.weight * 100).toFixed(2)
                      }}%
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-form>
        </template>
      </el-col>
    </el-row>

    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :disabled="disabled" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {doDelete, getList as getSonList} from '@/api/bom/bom'
import {getList as getAreaList} from '@/api/business/customer'
import {all as getList} from '@/api/sku/classify'
import {detailCateories, getPinYin} from '@/api/sku/mold'
import {doEdit} from '@/api/bom/bom'
import Upload from '@/views/other/upload/SingleImage3'
import AttachmentUpload from "@/views/other/upload/attachment";

export default {
  watch: {
    '$route'(to, from) {
      // 路由变化时重新加载数据
      if (to.path === '/bom/order') {
        // 路由变化为当前页时重新加载数据
        this.handleQueryss();
      }
    }
  },
  name: 'edit',
  components: {AttachmentUpload, Upload},
  data() {
    return {
      disabled: false,
      form: {
        pic: '',
        file_path: '',
        children: [],
        attribute_name: [],
        attribute_spec: [],
        sku_mold_id: 0,
        parentSku:{
          id:0,
          label:'无'
        },
      },
      rules: {
        no: [
          {required: true, trigger: 'blur', message: '请填写批次号'},
        ],
        customer_id: [
          {required: true, trigger: 'blur', message: '请填写地址'},
        ],
        code: [
          {required: true, trigger: 'blur', message: '请填写编码'},
        ],
        production_date: [
          {required: true, trigger: 'blur', message: '请填写生产日期'},
        ],
        weight: [
          {required: true, trigger: 'blur', message: '请填写重量(KG)'},
        ],
        sku_id: [
          {required: true, trigger: 'blur', message: '请选择SKU'},
        ],
      },
      title: '',
      dialogFormVisible: false,
      sku_list: [],
      customer_list: [],
      fileRootPath: process.env.VUE_APP_FILE_ROOT_PATH,
      children: [],
      mold_id: 0,


    }
  },
  created() {
    this.handleQueryss()
  },
  methods: {
    getSelectedLabel(skuId) {
      const item = this.sku_list.find((item) => item.id === skuId);
      return item ? item.label : "请选择";
    },
    handleChange() {
      if (this.form.sku_id) {
        this.mold_id = this.sku_list.find(item => item.id === this.form.sku_id).mold_id;
        detailCateories({id: this.mold_id, production_attribute: 2}).then((response) => {
          this.form.attribute_name = response.data.attrNameList
          this.form.attribute_spec = response.data.attrSpecList
        })
      } else {
        this.form.attribute_name = []
        this.form.attribute_spec = []
      }
    },
    handleChangeChildren(index) {
      if (this.form.children[index].sku_id) {
        let mold_id = this.sku_list.find(item => item.id === this.form.children[index].sku_id).mold_id;
        detailCateories({id: mold_id, production_attribute: 2}).then((response) => {
          this.form.children[index].attribute_name = response.data.attrNameList
          this.form.children[index].attribute_spec = response.data.attrSpecList
        })
      } else {
        this.form.children[index].attribute_name = []
        this.form.children[index].attribute_spec = []
      }
    },
    changeUrl(data) {
      this.form.tempPath = data.tempPath
      this.form.fileType = data.fileType
    },
    changeUrlFile(data) {
      this.form.tempPath_file = data.tempPath
      this.form.fileType_file = data.fileType
    },
    changeUrlFileChildren(data,index) {
      this.form.children[index].tempPath_file = data.tempPath
      this.form.children[index].fileType_file = data.fileType
    },
    handleQueryss() {
      getList({'pageNo': 'all'}).then(({data}) => {
        this.sku_list = data.list;
      });
      getAreaList({'pageNo': 'all', 'relationship': '3'}).then(({data}) => {
        this.customer_list = data.list;
      });
    },
    delete_file_children(index){
      this.form.children[index].temp_old_file = this.form.children[index].file_path
      this.form.children[index].file_path = ''
    },
    delete_file() {
      this.form.file_path = ''
    },
    delete_img() {
      this.form.pic = ''
    },
    pinyin() {
      getPinYin({'name': this.form.name}).then(response => {
        this.form.code = response.data.code
      })
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    showEdit(row) {
      if (!row) {
        this.title = '添加BOM工单'
        this.form.temp_old = ''
        this.form.temp_old_file = ''
        this.form.children = []
        this.form.is_link = 1
      } else {
        if(row.id) {
          if(row.is_link)
            this.title = '编辑挂靠BOM工单'
          else
            this.title= '编辑BOM工单'
          this.form = Object.assign({}, row)
          this.form.temp_old = this.form.pic
          this.form.temp_old_file = this.form.file_path
        }else{
          this.title = '挂靠BOM工单'
          this.form = Object.assign({}, row)
        }
      }
      this.dialogFormVisible = true
      this.disabled = false
    },

    viewEdit(row) {
      this.title = '查看BOM工单'
      this.form = Object.assign({}, row)
      this.dialogFormVisible = true
      this.disabled = true

    },
    close() {
      console.log(this.$refs['form'])
      this.$refs['form'].resetFields()
      if (this.$refs['uploadPic'])
        this.$refs['uploadPic'].resetTempUrl()
      if (this.$refs['uploadFile'])
        this.$refs['uploadFile'].resetTempUrl()
      this.form = this.$options.data().form
      this.dialogFormVisible = false
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const {msg} = await doEdit(this.form)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.$emit('fetch-data')
          this.close()
        }
      })
    },
    handleAddRow() {
      let obj = this.form.children
      obj.push({
        id: '',
        weight: 0,
        attribute_name: [],
        attribute_spec: [],
      });
    },
    handleDel(index) {
      this.$baseConfirm('你确定要永久删除当前行吗', null, async () => {
        let obj = this.form.children
        if(obj[index].id){
          const {msg} = await doDelete({ids: obj[index].id})
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
        }
        obj.splice(index, 1);
      })
    },
    handleUp(index) {
      let obj = this.form.children
      obj.splice(index - 1, 1, ...obj.splice(index, 1, obj[index - 1]));
    },
    handleDown(index) {
      let obj = this.form.children
      obj.splice(index, 1, ...obj.splice(index + 1, 1, obj[index]));
    }
  }
  ,
}
</script>
<style scoped>
.el-row {
  margin-bottom: 10px;
}

.row-with-margin {
  margin-bottom: 5px; /* 你可以根据需要调整这个值 */
}

.gap {
  /* 如果你已经有了gap类，确保它不会影响布局 */
}

.text-left {
  text-align: left;
}
</style>
